package com.study.lucene;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.store.NIOFSDirectory;

import java.io.IOException;
import java.nio.file.Paths;
public class IndexWriterExample {
    public static void write()throws IOException {
        // 使用NIOFSDirectory创建索引目录
        Directory directory = new NIOFSDirectory(Paths.get("D:\\Users\\门博\\IdeaProjects\\dbsyncer\\data\\a"));

        // 配置索引写入器
        IndexWriterConfig config = new IndexWriterConfig(
                new StandardAnalyzer() // 使用StandardAnalyzer进行文本分析
        );

        // 创建索引写入器
        IndexWriter indexWriter = new IndexWriter(directory, config);

        // 准备文档并添加到索引
        Document doc = new Document();
        doc.add(new TextField("content2", "example 2.", Field.Store.YES));

        // 添加文档
        indexWriter.addDocument(doc);

        // 提交更改
        indexWriter.commit();

        // 关闭写入器
        indexWriter.close();

        // 最后，关闭目录（实际上，NIOFSDirectory在IndexWriter关闭时也会被关闭）
        // directory.close(); 一般情况下可以省略，因为IndexWriter.close()已经关闭了它

        System.out.println("Document indexed successfully!");
    }

    public static void read(){
        try {
            // 索引存放的目录路径，与创建索引时指定的路径相同
            String indexPath = "D:\\Users\\门博\\IdeaProjects\\dbsyncer\\data\\a";

            // 使用FSDirectory打开索引目录，NIOFSDirectory也可以，根据实际情况选择
            Directory directory = FSDirectory.open(Paths.get(indexPath));

            // 获取IndexReader实例
            IndexReader indexReader = DirectoryReader.open(directory);

            // 创建IndexSearcher，用于执行搜索操作
            IndexSearcher searcher = new IndexSearcher(indexReader);

            // 创建QueryParser，用于解析查询语句，这里以"content"字段为例
            QueryParser queryParser = new QueryParser("content2", new StandardAnalyzer());

            // 构建查询
            String queryText = "example 2."; // 要搜索的关键词
            Query query = queryParser.parse(queryText);

            // 执行搜索，返回最相关的前10个结果
            TopDocs topDocs = searcher.search(query, 10);

            // 输出匹配的文档信息
            System.out.println("Found " + topDocs.totalHits.value + " hits.");
            for (ScoreDoc scoreDoc : topDocs.scoreDocs) {
                Document doc = searcher.doc(scoreDoc.doc);
                System.out.println("DocId: " + scoreDoc.doc + ", Score: " + scoreDoc.score);
                System.out.println("Content: " + doc.get("content2"));
            }
            // 关闭IndexReader
            indexReader.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws Exception{
       // write();
        read();
    }
}
